﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows;

namespace XMM
{
    public class ItemChecks
    {
        /// <summary>
        /// Check if File Exists as any Item in Database.
        /// </summary>
        /// <param name="sFilePath">(string) Full Path to search for.</param>
        /// <returns>[true] if the file exists in any db-item or [false] if the file wasn't found.</returns>
        public static bool checkFileExists(string sFilePath)
        {
            // Remove Drive-Letter and Seperator-Char (').
            string sReducedFilePath = sFilePath.Remove(0, 2);
            //sReducedFilePath = sReducedFilePath.Remove((sReducedFilePath.Length - 1), 1);

            try
            {
                XMMDBDataContext dbConnection = new XMMDBDataContext();

                // Get an array of all Movie-File-Strings in database.
                var vMovies = from movies in dbConnection.t_movies select movies.Files;

                // Check if any File-Strings were found.
                if (vMovies != null)
                {
                    // Check each File-String if it contains the search-string.
                    foreach (string sFilesString in vMovies)
                    {
                        if (sFilesString.Contains(sReducedFilePath))
                        {
                            // If this File-String contains the search-string, return true.
                            return true;
                        }
                    }
                }

                // Get an array of all Episode-File-Strings.
                var vEpisodes = from episodes in dbConnection.t_series_episodes select episodes.Files;

                // Check fi any File-Strings were found.
                if (vEpisodes != null)
                {
                    // Check each file-String if it contais the search-string.
                    foreach (string sFileString in vEpisodes)
                    {
                        if (sFileString.Contains(sReducedFilePath))
                        {
                            // If this File-String contains the search-string, return true.
                            return true;
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Fehler beim Überprüfen der Existenz von Datei \"" + sFilePath + "\": " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return false;
        }
    }
}
